<%@ page language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="auth" uri="http://www.jiyinit.com/authTag"%>
<!DOCTYPE html>

<link rel="stylesheet" href="${basePath}/plugins/ztree/zTreeStyle/zTreeStyle.css${VERSION}" type="text/css">

<div class="right-container">
    <div class="row">
        <div class="col-sm-4">
            <div class="widget-box widget-color-blue2">
                <div class="widget-header">
                    <h4 class="widget-title lighter smaller">功能树</h4>
                </div>

                <div class="widget-body">
                    <div class="widget-main padding-8">
                        <ul id="tree" class="ztree"></ul>
                        <ul class="list">
                            [ <a id="expandAllBtn" href="#" onclick="return false;">全部展开</a> ]
                            [ <a id="resetBtn" href="#" onclick="return false;">重置</a> ]
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-8">
            <div class="widget-box widget-color-green2">
                <div class="widget-header">
                    <h4 class="widget-title lighter smaller">功能列表</h4>
                </div>
                <div class="widget-body">
                    <div class="widget-main padding-8">
                        <div class="manage-button text-left">
                           <auth:auth authUrl="fun/toAdd">
                                <button id="addButton" class="btn btn-primary" type="button">
                                    <i class="fa fa-plus"></i> 新增
                                </button>
                            </auth:auth>
                            <auth:auth authUrl="fun/toUpdate">
                                <button id="updateButton" class="btn btn-primary" type="button">
                                    <i class="fa fa-pencil"></i> 修改
                                </button>
                            </auth:auth>
                            <auth:auth authUrl="fun/delete">
                                <button id="deleteButton" class="btn btn-primary" type="button">
                                    <i class="fa fa-pencil"></i> 删除
                                </button>
                            </auth:auth>
                        </div>
                        <div class="col-xs-12">
                            <table id="grid-table"></table>
                            <div id="grid-pager"></div>
                        </div>
                        <div class="clear"></div>
                        <input type="hidden" id="parentId">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- page specific plugin scripts -->
<script src="${basePath}/plugins/ztree/jquery.ztree.core.js${VERSION}"></script>
<script src="${basePath}/plugins/jqGrid/jquery.jqGrid.min.js${VERSION}"></script>
<script src="${basePath}/plugins/jqGrid/grid.locale-cn.js${VERSION}"></script>
<!-- inline scripts related to this page -->
<script type="text/javascript">
    var setting = {
        async: {
            enable: true,
            url:"${basePath}/fun/getTreeByParent",
            autoParam:["id=parentId"],
            //otherParam:{"otherParam":"zTreeAsyncTest"},
            dataFilter: filter,
            dataType:"json",
            type: "post"
        },
        callback: {
            beforeAsync: beforeAsync,
            onAsyncSuccess: onAsyncSuccess,
            onAsyncError: onAsyncError,
            onClick: onClick
        }
    };
    var curStatus = "init", curAsyncCount = 0, asyncForAll = false, goAsync = false;
    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        var data = childNodes.data;
        for (var i=0, l=childNodes.length; i<l; i++) {
            data[i].name = data[i].name.replace(/\.n/g, '.');
        }
        return data;
    }
    function beforeAsync() {
        curAsyncCount++;
    }
    function onAsyncSuccess(event, treeId, treeNode, msg) {
        curAsyncCount--;
        if (curStatus == "expand") {
            expandNodes(treeNode.children);
        } else if (curStatus == "async") {
            asyncNodes(treeNode.children);
        }

        if (curAsyncCount <= 0) {
            if (curStatus != "init" && curStatus != "") {
                asyncForAll = true;
            }
            curStatus = "";
        }
    }
    function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
        curAsyncCount--;

        if (curAsyncCount <= 0) {
            curStatus = "";
            if (treeNode!=null) asyncForAll = true;
        }
    }
    function expandAll() {
        if (!check()) {
            return;
        }
        var zTree = $.fn.zTree.getZTreeObj("tree");
        if (asyncForAll) {
            zTree.expandAll(true);
        } else {
            expandNodes(zTree.getNodes());
            if (!goAsync) {
                curStatus = "";
            }
        }
    }
    function expandNodes(nodes) {
        if (!nodes) return;
        curStatus = "expand";
        var zTree = $.fn.zTree.getZTreeObj("tree");
        for (var i=0, l=nodes.length; i<l; i++) {
            zTree.expandNode(nodes[i], true, false, false);
            if (nodes[i].isParent && nodes[i].zAsync) {
                expandNodes(nodes[i].children);
            } else {
                goAsync = true;
            }
        }
    }
    function asyncNodes(nodes) {
        if (!nodes) return;
        curStatus = "async";
        var zTree = $.fn.zTree.getZTreeObj("tree");
        for (var i=0, l=nodes.length; i<l; i++) {
            if (nodes[i].isParent && nodes[i].zAsync) {
                asyncNodes(nodes[i].children);
            } else {
                goAsync = true;
                zTree.reAsyncChildNodes(nodes[i], "refresh", true);
            }
        }
    }
    function reset() {
        if (!check()) {
            return;
        }
        asyncForAll = false;
        goAsync = false;
        $.fn.zTree.init($("#tree"), setting);
    }
    function check() {
        if (curAsyncCount > 0) {
            return false;
        }
        return true;
    }
    var curNode;
    function onClick(event, treeId, treeNode, clickFlag) {
        query(treeNode.id);
        curNode = treeNode;
    }
    function refreshCurNode() {
        if(curNode != null){
            var zTree = $.fn.zTree.getZTreeObj("tree");
            zTree.reAsyncChildNodes(curNode, "refresh", true);
        }
    }
    $(function() {
        $.fn.zTree.init($("#tree"), setting);
        $("#expandAllBtn").bind("click", expandAll);
        $("#resetBtn").bind("click", reset);
        CommonUtils.grid({
            url: "${basePath}/fun/findPageByParentId",
            colNames: ['ID', '功能名称', '功能类型','排序','创建人ID', '创建时间'],
            colModel: [
                {name: 'funId', index: 'funId'},
                {name: 'funName', index: 'funName', width: 100},
                {name: 'funType', index: 'funType', width: 60,formatter:showType},
                {name: 'funOrderBy', index: 'funOrderBy', width: 60},
                {name: 'createName', index: 'createName', width: 50},
                {name: 'createTime', index: 'createTime', width: 100, formatter: CommonUtils.formateDate},
            ],
            jsonReader: {
                root:"rows", page:"currentPage", total:"totalPages",
                records:"totalRecords", repeatitems:false, id : "resourceId"
            }
        });
    });

    function query(parentId){
        $("#parentId").val(parentId);
        $("#grid-table").jqGrid('setGridParam',{
            url: "${basePath}/fun/findPageByParentId",
            postData:{
                parentId: parentId
            }, //发送数据
            page:1
        }).trigger("reloadGrid"); //重新载入
    }

    var pageDialog = null;
    $("#addButton").click("click", function () {
        var parentId = $("#parentId").val();
        if(parentId=='' || parentId==null){
            layer.msg("请先选择需要添加的父级功能！");
            return;
        }
        pageDialog = layer.open({
            title: "新增功能",
            type: 2,
            area: ["800px", "500px"],
            content: '${basePath}/fun/toAdd?parentId=' + parentId
        });
    });
    $("#updateButton").click("click", function () {
        var ids=$('#grid-table').jqGrid('getGridParam','selarrrow');
        if(ids.length>=2 || ids==''){
            layer.msg("请选择1行数据进行修改！");
            return;
        }

        var rowData = $("#grid-table").jqGrid('getRowData', ids);
        var funId = rowData.funId;

        pageDialog = layer.open({
            title: "修改功能",
            type: 2,
            area: ["800px", "500px"],
            content: '${basePath}/fun/toUpdate?funId=' + funId
        });
    });
    function showType(value, row, index){
        if(value == "1"){
            return "默认";
        }else if(value == "2"){
            return "普通";
        }else if(value == "3"){
            return "定制"
        }else {
            return ""
        }
    }
    var loading = null;
    $('#deleteButton').click("click", function () {
        var rowsIds = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if (rowsIds.length <= 0  || rowsIds == "") {
            layer.msg("请至少选择一行数据进行删除！");
            return;
        }
        var funIds = [];
        $(rowsIds).each(function () {
            var rowData = $("#grid-table").jqGrid('getRowData', this);
            funIds.push(rowData.funId);
        });

        //删除校验
        $.ajax({
            type: "post",
            data: "funIds=" + funIds,
            url: "${basePath}/fun/funDeleteCheck",
            dataType: "json",
            beforeSend:function () {
                $('#deleteButton').prop("disabled", true);
                loading = layer.load(0, {
                    shade: [0.4,'#fff'] //0.4透明度的白色背景
                });
            },
            success: function (data) {
                $('#deleteButton').prop("disabled", false);
                layer.close(loading);
                if (data.status == "0") {

                layer.confirm('是否删除选中数据？',{ icon: 3}, function (index) {

                    $.ajax({
                        type: "post",
                        data: "funIds=" + funIds,
                        url: "${basePath}/fun/delete",
                        dataType: "json",
                        beforeSend:function () {
                            $('#deleteButton').prop("disabled", true);
                            loading = layer.load(0, {
                                shade: [0.4,'#fff'] //0.4透明度的白色背景
                            });
                        },
                        success: function (data) {
                            $('#deleteButton').prop("disabled", false);
                            layer.close(loading);
                            if (data.status == "0") {
                                layer.msg("删除成功！");
                                $("#grid-table").jqGrid().trigger("reloadGrid", [{page: 1}]);
                            }else {
                                layer.alert(data.message, {
                                    icon: 0,
                                    skin: 'layui-layer-lan',
                                    closeBtn: 0
                                })
                            }
                        },
                        error: function(xhr, textStatus, errorThrown) {
                            $('#deleteButton').prop("disabled", false);
                            layer.close(loading);
                        }
                    });
                    return false;
                });
                }else {
                    layer.alert("所选功能有子功能不允许删除", {
                        icon: 0,
                        skin: 'layui-layer-lan',
                        closeBtn: 0
                    })
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                $('#deleteButton').prop("disabled", false);
                layer.close(loading);
            }
        });
    });
</script>
